import { Space, Select, Button, Tag, Spin } from 'antd';
import { useState, useEffect } from 'react';
import { useRequest, useUpdate } from '@umijs/hooks';
import { fuzzyQueryEnterprises } from '@/services/zhirong/enterprise';
import { getAssociateEntity } from '@/services/zhirong/associate';
import { getEquityNetwork } from '@/services/zhirong/equity';

const { Option } = Select;

const CustomizedInput = (props) => {
  // 模糊查询得到的企业列表状态
  const [enterpriseList, setEnterpriseList] = useState([]);
  // 从列表中选定的企业状态
  const [enterprise, setEnterprise] = useState({
    name: null,
    eid: '',
    status: '',
  });
  useEffect(() => {
    if (enterprise.eid) {
      props.onSelect(enterprise, props.role);
    }
  }, [enterprise]);

  // 输入的查询词状态，用于在下拉列表中进行高亮显示
  const [query, setQuery] = useState('');
  useEffect(() => {
    if (props.forceSet && props.forceSet.eid && props.forceSet.FullName) {
      setEnterpriseList([props.forceSet]);
      setEnterprise(props.forceSet);
      setQuery(props.forceSet.FullName);
    }
  }, [props.forceSet]);
  // 使用防抖的异步请求hook进行模糊查询
  const { loading, run } = useRequest(fuzzyQueryEnterprises, {
    debounceInterval: 800,
    manual: true,
    onSuccess: (result) => {
      if (result && result.code === 0) {
        setEnterpriseList(result.data.enterpriseList);
      } else {
        console.log('msg:', result.msg);
      }
      console.log('loading:', loading);
    },
    onError: (err) => {
      console.log('err:', err);
    },
  });
  // select框输入行为所触发的函数，发送异步请求获取企业列表
  const handleSearch = (queryWords) => {
    if (queryWords && queryWords.length > 1) {
      setQuery(queryWords);
      run({
        query: queryWords,
        limit: 5,
        ts: new Date().getTime(),
      });
    } else {
      setEnterpriseList([]);
    }
  };
  // select下拉列表选择企业所触发的函数，确定目标企业更新选定企业状态并更新查询词为目标企业名
  const handleChange = (eid) => {
    console.log('来自select组件', eid);
    let [target] = enterpriseList.filter((item) => item.eid === eid);
    setEnterprise(target);
    setQuery(target.FullName);
  };

  const hightlightQuery = (name) => {
    if (name) {
      const startIndex = name.indexOf(query);
      const queryLength = query.length;
      // console.log(name,query, name.slice(0, startIndex))
      return (
        <>
          {startIndex === -1 ? (
            <span>{name}</span>
          ) : (
            <span>
              {name.slice(0, startIndex)}
              <span style={{ color: 'red' }}>{name.substr(startIndex, queryLength)}</span>
              {name.slice(startIndex + queryLength)}
            </span>
          )}
        </>
      );
    }
  };

  const options = enterpriseList.map((item) => (
    <Option key={item.eid}>
      <Space>
        {hightlightQuery(item.FullName)}
        {item.Status === '存续（在营、开业、在册）' && <Tag color="blue">存续</Tag>}
        {item.Status === '注销' && <Tag color="orange">注销</Tag>}
        {item.Status === '迁出' && <Tag color="orange">迁出</Tag>}
        {String(item.Status).indexOf('吊销') !== -1 && <Tag color="red">吊销</Tag>}
      </Space>
    </Option>
  ));

  return (
    <Select
      showSearch
      showArrow={false}
      value={query == '' ? null : query}
      placeholder={props.placeholder}
      style={props.style}
      defaultActiveFirstOption={false}
      filterOption={false}
      onSearch={handleSearch}
      onChange={handleChange}
      notFoundContent={loading ? <Spin size="small" tip="搜索中" /> : null}
    >
      {options}
    </Select>
  );
};

const SecondInput = (props) => {
  const [enterpriseList, setEnterpriseList] = useState([]);

  const { firstEnterprise } = props;
  const { run } = useRequest(getEquityNetwork, {
    manual: true,
    onSuccess: (res) => {
      const list = res.data.nodes;
      list.forEach((e) => {
        e.eid = e.id;
      });
      setEnterpriseList(list);
    },
  });
  // 从列表中选定的企业状态
  const [enterprise, setEnterprise] = useState({
    name: null,
    eid: '',
    status: '',
  });

  useEffect(() => {
    if (enterprise.eid) {
      props.onSelect(enterprise, props.role);
    }
  }, [enterprise]);
  useEffect(() => {
    if (firstEnterprise?.eid) {
      setEnterpriseList([]);
      run({
        centerId: firstEnterprise.eid,
        level: 5,
        direction: 0,
        dateFrom: '2018-01-01',
        dateTo: '2018-12-31',
      });
    }
  }, [firstEnterprise, run]);

  // select下拉列表选择企业所触发的函数，确定目标企业更新选定企业状态并更新查询词为目标企业名
  const handleChange = (eid) => {
    const [target] = enterpriseList.filter((item) => item.eid === eid);
    setEnterprise(target);
  };

  return (
    <Select
      showSearch
      showArrow={false}
      value={enterprise.name}
      placeholder={props.placeholder}
      style={props.style}
      onChange={handleChange}
      disabled={!firstEnterprise?.eid}
      optionFilterProp="children"
      filterOption={(input, option) => option.children.indexOf(input.toLowerCase()) >= 0}
    >
      {enterpriseList.map((item) => (
        <Option key={item.eid}>{item.name}</Option>
      ))}
    </Select>
  );
};

const BiSearchBox = (props) => {
  // 从列表中选定的企业状态
  const [enterprises, setEnterprises] = useState({
    enterpriseA: {
      name: null,
      eid: '',
      status: '',
    },
    enterpriseB: {
      name: null,
      eid: '',
      status: '',
    },
  });
  const [forceSet, setForceSet] = useState();
  const handleSelected = (value, role) => {
    console.log("aaaa", value)
    if (role === 'A') {
      setEnterprises({
        ...enterprises,
        enterpriseB: value,
      });
    } else {
      setEnterprises({
        ...enterprises,
        enterpriseA: value,
      });
    }
  };
  // 点击查询button触发的函数，用户将查询的目标企业信息参数传递给父组件，并通过父组件将参数派发其他功能性子组件
  const handleClick = () => {
    console.log("点击", enterprises)
    props.onSubmit(enterprises);
  };

  return (
    <Space direction="vertical" size="small" >
      <Space>
        <CustomizedInput
          onSelect={handleSelected}
          role="A"
          placeholder={'请手动输入您要查询的企业名称'}
          style={{ width: 250 }}
          forceSet={forceSet}
        />
        <SecondInput
          firstEnterprise={enterprises.enterpriseB}
          onSelect={handleSelected}
          role="B"
          placeholder={'请选择您要查询的企业名称'}
          style={{ width: 250 }}
        />
        <Button type="primary" onClick={handleClick}>
          查询
        </Button>
      </Space>
      <Space style={{ color: '#999999' }} >
        搜索建议:
        {props.advices?.map((advice) => (
          <Button
            key={advice.length}
            onClick={() => {
              //  props.onSubmit(advice);
              setForceSet(advice);
            }}
            style={{ backgroundColor: '#F7F7F7', color: '#999999' }}
          >
            {advice.FullName}
          </Button>
        ))}
      </Space>
    </Space>
  );
};

export default BiSearchBox;
